﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;
using System.Text.RegularExpressions;
using Empires.CRL.DataContract;
using Empires.PL.ServiceClient;

namespace Empires.PL.PageHandler
{
    public enum AccessType
    { 
        Group,Master
    }
    public class CompanyAuthAttribute : AuthorizeAttribute
    {
        private AccessType type;
        private AuthGroup group;
        /// <summary>
        /// 限制只有Master能访问
        /// </summary>
        public CompanyAuthAttribute()
        {
            this.type = AccessType.Master;
        }
        /// <summary>
        /// Group模式
        /// </summary>
        /// <param name="group">允许访问的组</param>
        public CompanyAuthAttribute(AuthGroup group)
        {
            this.type = AccessType.Group;
            this.group = group;
        }
        protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
        {
            string copname = string.Empty;
            string host = httpContext.Request.Headers["host"];
            string regexp = "(www\\.)?(?<id>\\w+?)\\.\\w+?\\.com.*";
            var reg = new Regex(regexp);
            var match = reg.Match(host);
            if (reg.Match(host).Success)
            {
                copname = match.Groups["id"].Value;
            }
            if (String.IsNullOrEmpty(copname)) //如果匹配公司名为空则验证失败
            {
                return false;
            }

            if ((group & AuthGroup.normal) != AuthGroup.normal && !httpContext.User.Identity.IsAuthenticated)
            {
                return false;
            } 
            switch (type)
            { 
                case  AccessType.Group:
                    var result = ServiceProviderServiceClient.GetAuthInfo(copname, httpContext.User.Identity.Name);
                    if (result != null && result.Any())
                    {
                        if ((group & (AuthGroup)(result[0].GROUP)) == (AuthGroup)(result[0].GROUP))
                        {
                            return true;
                        }
                    }
                    return false; //按照分组验证，暂未实现
                case  AccessType.Master: 
                    if (httpContext.User.Identity.Name == Empires.PL.ServiceClient.CompanyBaseServiceClient.GetMasterName(copname))
                    {
                        return true;
                    }
                    return false;
                default:
                    return false;
            }
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            filterContext.HttpContext.Response.Redirect("/SignIn");
        }
    }
}
